package com.weishenai.customerassistant.service.impl;

import cn.hutool.extra.qrcode.QrCodeException;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.weishenai.customerassistant.service.QrCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

@Service
@Slf4j
public class QrCodeServiceImpl implements QrCodeService {
    @Value("${file.wechatAppIconPath}")
    private String wechatIconPath;

    private QrConfig initQrConfig(){
        QrConfig config = new QrConfig(300, 300);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(3);
        // 设置前景色，既二维码颜色（青色）
        config.setForeColor(Color.BLACK);
        // 设置背景色（灰色）
        config.setBackColor(Color.WHITE);
        // 设置logo
        config.setImg(wechatIconPath);
        return config;
    }

    @Override
    public void createCodeToStream(String content, HttpServletResponse response) {

        try {
            BufferedImage bufferedImage = QrCodeUtil.generate(content,initQrConfig());
            //以JPEG格式向客户端发送
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("image/jpeg");
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(bufferedImage, "png",os);
            os.flush();
            os.close();
        } catch (QrCodeException | IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object createdCodeToBase64(String content) {
        String base64Img = null;
        try {
            BufferedImage bufferedImage = QrCodeUtil.generate(content,initQrConfig());
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
            String str = "data:image/jpeg;base64,";
            base64Img = str + Base64.getEncoder().encodeToString(outputStream.toByteArray());
        }catch (IOException e) {
            e.printStackTrace();
        }
        return base64Img;
    }

}
